import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar 进度条组件
import 'nprogress/nprogress.css' // progress bar style 进度条样式
import { getToken } from '@/utils/auth' // get token from cookie  获取本地存储的Token
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration 配置进度条

const whiteList = ['/login'] // no redirect whitelist 白名单
// 前置守卫
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  // 获取Token判断是否登录
  const hasToken = getToken()

  if (hasToken) {
    // 如果登录了有Toekn
    // 如果还是去登录页面则直接跳转主页
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // 登陆了，但是去的不是登录页
      // 有用户名就放行
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
        // 没有用户名称就获取用户资料
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')
          next()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    // 如果没有登录，且要去的地址在白名单中就直接跳转
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
      // 如果没登录就拦截跳转到登录页面，登录后返回原本要去的页面
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})
// 后置守卫
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
